<template>
    <el-textarea v-if="illegalActText !== ''" class="span-underline" @click="showLawsModal()">
        {{ illegalActText }}
    </el-textarea>
    <span v-else @click="showLawsModal()"
        :style="{ borderBottom: '1px solid black', width: width, display: 'inline-block' }">&nbsp;
    </span>

    <el-dialog v-model="showModal" :close-on-click-modal="false" width="1300px" align-center text-align: title="选择违法行为"
        :before-close="cleanLawsModal">
        <div>
            <div><img src="../../assets/logo.png"
                    style="width: 40px;height:40px;margin-left: 20px;vertical-align: middle;" />
                <span style="font-size: 5mm;">{{ popTitleName }}</span>
            </div>
            <div style="margin:5px 10px;">
                <el-input v-model="returnData.returnIllegalAct" placeholder="请输入您要填入表单的违法行为" style="margin-right: 5px"
                    clearable />
            </div>
            <div style="padding: 10px;display: flex">
                <el-input v-model="illegalAct" placeholder="请输入你要查询的违法行为" style="width: 300px;margin-right: 5px"
                    clearable />
                <el-button type="primary" style="margin-left: 5px" @click="searchLawsAndRegulations">搜索</el-button>
            </div>
            <hr class="yanse" border>
            <div class="lawsAndRegulationsTable">
                <el-table :data="tableData" border stripe style="width: 100%" :height="500" @row-click="selectLawsData">
                    <el-table-column align="center" prop="illegalAct" label="违法行为" width="200"></el-table-column>
                    <el-table-column align="center" prop="illegalTermsString" label="违反条款" width="300">
                        <template v-slot="{ row }">
                            <div class="formatted-text">{{ row.illegalTermsString }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="illegalBasisString" label="处罚依据" width="300">
                        <template v-slot="{ row }">
                            <div class="formatted-text">{{ row.illegalBasisString }}</div>
                        </template>
                    </el-table-column>

                    <el-table-column align="center" label="较轻情形">
                        <el-table-column align="center" prop="slightPlotConsequences" label="违法情节和后果"
                            width="200"></el-table-column>
                        <el-table-column align="center" prop="slightPunishmentStandards" label="处罚标准"
                            width="200"></el-table-column>
                    </el-table-column>

                    <el-table-column align="center" label="一般情形">
                        <el-table-column align="center" prop="generalPlotConsequences" label="违法情节和后果"
                            width="200"></el-table-column>
                        <el-table-column align="center" prop="generalPunishmentStandards" label="处罚标准"
                            width="200"></el-table-column>
                    </el-table-column>

                    <el-table-column align="center" label="严重情形">
                        <el-table-column align="center" prop="seriousPlotConsequences" label="违法情节和后果"
                            width="200"></el-table-column>
                        <el-table-column align="center" prop="seriousPunishmentStandards" label="处罚标准"
                            width="200"></el-table-column>
                    </el-table-column>


                    <!-- <el-table-column align="center" prop="operate" label="操作" width="200" fixed="right">
                        <template v-slot="scope">
                            <el-button type="primary" size="small" icon="Edit"
                                @click.native.stop="selectLawsData(scope.row)">选择</el-button>
                        </template>
                    </el-table-column> -->
                </el-table>
                <div class="footer">
                    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                        :page-sizes="[5, 10, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                    </el-pagination>
                </div>
            </div>
        </div>
    </el-dialog>

</template>

<script>
import request from '@/utils/request';
import { popTitleName } from "../../utils/publicName.js"
export default {
    props: {
        width: {
            type: String,
            default: ''
        },
        illegalActText: {
            type: String,
            default: ''
        },
        returnIllegalTermsString: {
            type: String,
            default: ''
        },
        returnIllegalBasisString: {
            type: String,
            default: ''
        },
    },
    data() {
        return {
            popTitleName: popTitleName,
            showModal: false,
            illegalAct: '',
            tableData: [],
            total: 0,
            pageNum: 1,
            pageSize: 5,

            returnData: {
                returnIllegalAct: '',
                returnIllegalTermsString: '',
                returnIllegalBasisString: '',
            }
        }
    },
    methods: {
        // 查询数据
        gettableData() {
            request.get("/laws-and-regulations/page", {
                params: {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                    search: this.illegalAct,
                }
            }).then(res => {
                if (res.code == '200') {
                    this.tableData = res.data.records
                    this.total = res.data.total
                }
            })
        },
        // 搜索
        searchLawsAndRegulations() {
            this.pageNum = 1;
            this.gettableData();
        },

        // 分页
        handleSizeChange(val) {
            this.pageSize = val;
            this.gettableData();
        },
        handleCurrentChange(val) {
            this.pageNum = val;
            this.gettableData();
        },
        // 选择
        selectLawsData(row) {
            request.get(`/laws-and-regulations/getTermObjectList`, {
                params: {
                    illegalTermsIds: row.illegalTerms,
                    illegalBasisIds: row.illegalBasis,
                },
                paramsSerializer: (params) => {
                    return Object.entries(params)
                        .flatMap(([key, values]) =>
                            Array.isArray(values)
                                ? values.map(value => `${key}=${encodeURIComponent(value)}`)
                                : `${key}=${encodeURIComponent(values)}`
                        )
                        .join('&');
                }
            }).then(res => {
                if (res.code === '200') {
                    if (this.returnData.returnIllegalAct === '') {
                        this.returnData.returnIllegalAct = row.illegalAct;
                    }
                    this.returnData.returnIllegalTermsString = this.handleJoin(res.data.illegalTermsObject)
                    this.returnData.returnIllegalBasisString = this.handleJoin(res.data.illegalBasisObject)
                    this.returnDataToFather()
                }
            })
        },
        // 处理拼接
        handleJoin(illegalObject) {
            // 中文数字映射表
            const chineseNumMap = {
                '一': 1, '二': 2, '三': 3, '四': 4, '五': 5,
                '六': 6, '七': 7, '八': 8, '九': 9, '十': 10
            };

            function chineseToNumber(str) {
                if (!str) return 0;
                // 处理“十”开头的数字
                if (str.startsWith('十')) {
                    if (str.length === 1) return 10;
                    return 10 + chineseNumMap[str[1]];
                }
                // 处理整十数
                if (str.endsWith('十')) {
                    return chineseNumMap[str[0]] * 10;
                }
                // 处理二十一组合数
                if (str.length === 2) {
                    return chineseNumMap[str[0]] * 10 + chineseNumMap[str[1]];
                }
                // 个位数
                return chineseNumMap[str] || 0;
            }

            // 提取层级数字
            function getLevelNumber(text) {
                if (!text) return 0;
                const match = text.match(/[一二三四五六七八九十]+/);
                return match ? chineseToNumber(match[0]) : 0;
            }

            // 按法律名称分组
            const grouped = {};
            illegalObject.forEach(item => {
                const lawName = item.lawName;
                if (!grouped[lawName]) {
                    grouped[lawName] = [];
                }
                grouped[lawName].push({
                    article: item.article,
                    paragraph: item.paragraph,
                    subparagraph: item.subparagraph,
                    item: item.item
                });
            });

            // 处理每组数据（排序+拼接）
            const resultArr = [];
            Object.entries(grouped).forEach(([lawName, items]) => {
                // 排序
                const sortedItems = items.sort((a, b) => {
                    const articleA = getLevelNumber(a.article);
                    const articleB = getLevelNumber(b.article);
                    if (articleA !== articleB) return articleA - articleB;

                    const paragraphA = getLevelNumber(a.paragraph);
                    const paragraphB = getLevelNumber(b.paragraph);
                    if (paragraphA !== paragraphB) return paragraphA - paragraphB;

                    const subparagraphA = getLevelNumber(a.subparagraph);
                    const subparagraphB = getLevelNumber(b.subparagraph);
                    if (subparagraphA !== subparagraphB) return subparagraphA - subparagraphB;

                    const itemA = getLevelNumber(a.item);
                    const itemB = getLevelNumber(b.item);
                    return itemA - itemB;
                });

                // 拼接每条的完整层级
                const articleStrs = sortedItems.map(item => {
                    let str = item.article || '';
                    if (item.paragraph) str += item.paragraph;
                    if (item.subparagraph) str += item.subparagraph;
                    if (item.item) str += item.item;
                    return str;
                });

                // 组合当前法律的结果
                resultArr.push(`${lawName}${articleStrs.join('、')}`);
            });

            // 拼接所有法律的结果
            const finalResult = resultArr.join('，');
            return finalResult;
        },
        // 返回数据
        returnDataToFather() {
            // 这里将数据返回给父组件
            this.$emit('update:illegalActText', this.returnData.returnIllegalAct);
            this.$emit('update:returnIllegalTermsString', this.returnData.returnIllegalTermsString);
            this.$emit('update:returnIllegalBasisString', this.returnData.returnIllegalBasisString);

            this.cleanLawsModal(); // 关闭弹窗

        },

        // 显示弹窗
        showLawsModal() {
            // 清空数据
            this.illegalAct = ''
            this.returnData.returnIllegalAct = ''
            this.returnData.returnIllegalTermsString = ''
            this.returnData.returnIllegalBasisString = ''
            this.gettableData()
            this.showModal = true
        },
        // 关闭弹窗
        cleanLawsModal() {
            this.showModal = false
        },
    }
}
</script>

<style scoped>
/* 违法行为弹窗回显文字下划线 */
.span-underline {
    text-decoration: underline;
    text-underline-offset: 4px;
    text-decoration-thickness: 0.5px;
}

.footer {
    padding: 4px 10px;
    background-color: #f4f3f9;
}

/* 违法行为识别\n换行 */
.formatted-text {
    text-align: left;
    white-space: pre-wrap;
}

:deep(.lawsAndRegulationsTable th),
:deep(.lawsAndRegulationsTable td) {
    border: 1px solid #ebeef5 !important;
}
</style>
